/* eslint-disable no-param-reassign */
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-console */
// import { getProductById } from '@/services/ant-design-pro/api';
import { getProductById } from '@/services/ant-design-pro/api';
import { getInfluxDataCount, getProductInfluxDataCountById, getProductStatesAllRefreshById, getProductStatesAllRefreshByImsi, getProductStatesAllViewById, getProductStatesAllViewByImsi } from '@/services/ant-design-pro/influxdb';
import { a_item_change, err_item_change, hz_item_change, sw_item_change, temper_item_change, v_item_change, w_item_change } from '@/services/ant-design-pro/itemchange';
import { Line } from '@ant-design/charts';
import ProCard from '@ant-design/pro-card';
import { GridContent } from '@ant-design/pro-layout';
import { Badge, Descriptions } from 'antd';
import moment from 'moment';
import React, { Suspense, useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { useModel, useRequest } from 'umi';
import { message } from 'antd';
import ProForm, { ProFormDateTimeRangePicker, ProFormDependency, ProFormSelect } from '@ant-design/pro-form';
import dayjs from 'dayjs';

// const aa = await dayjs_getGreeProductStates_temper(3,deviceimsi)
// console.log({"aa":aa.data})

/* const bb = await getProductStates(3, deviceimsi)
console.log({ "group": bb }) */

// const DevStates: React.FC = (props?: any) => {
const DevStates: React.FC = () => {

  const { initialState } = useModel('@@initialState');
  const { state } = useLocation();
  const [dataSw, setDataSw] = useState<API.DevStatesItem[]>([]);
  const [dataTemper, setDataTemper] = useState<API.DevStatesItem[]>([]);
  const [dataHz, setDataHz] = useState<API.DevStatesItem[]>([]);
  const [dataW, setDataW] = useState<API.DevStatesItem[]>([]);
  const [dataA, setDataA] = useState<API.DevStatesItem[]>([]);
  const [dataV, setDataV] = useState<API.DevStatesItem[]>([]);
  const [dataErr, setDataErr] = useState<API.DevStatesItem[]>([]);
  // get数据刷新时间
  const [viewValues, setViewValues] = useState<API.ViewValues>({
    viewMode: 1,
    forepartTime: 30,
    refreshTime: 10000,  // 暂时不用
    startTime: dayjs().subtract(1, 'hour').unix(),
    stopTime: dayjs().unix(),
  });

  // const [data2, setData2] = useState([]);
  /*   const devselect: API.GreeProductItem = JSON.parse(props?.location?.query?.devselect) || {}
    console.log("devselect:",devselect) */

  // const [product, setProduct] = useState<API.GreeProductItem>();
  // const devid = initialState?.device_id;
  //   const deviceimsi = initialState?.device_imsi || "";
  // 刷新后不保存，不用
  // console.log("devid:",devid)
  // 刷新后保存，启用
  // console.log("state:",state)

  const deviceimsi: string = state ? state.device_imsi : (initialState?.device_imsi || "");
  const devid = state ? state.device_id : initialState?.device_id;

  const product = useRequest(() => { return getProductById(devid || 0) }, {
    pollingInterval: 10000, // 10S
    // pollingInterval: 0,  //0 不刷新
    pollingWhenHidden: false,
  }).data   // || initialState?.device_select;

  // console.log("product:",product)

  // const product = product_res.data  || initialState?.device_select

  const { run } = useRequest(() => { return getProductStatesAllViewById(devid, viewValues) });
  // const { run } = useRequest(() => { return getProductStatesAllViewByImsi(deviceimsi, viewValues) });

  const reloaddata = async () => {
    run().then((res => {
      // console.log("res:", res);
      const sw = sw_item_change(res?.datasw || []);
      const temper = temper_item_change(res?.datatemper || []);
      const a = a_item_change(res?.dataa || []);
      const v = v_item_change(res?.datav || []);
      const w = w_item_change(res?.dataw || []);
      const hz = hz_item_change(res?.datahz || []);
      const err = res?.datasw.filter(item => item._field === '故障').concat(err_item_change(res?.dataerr)) || [];
      // console.log("sw0:", sw);
      // console.log("temper0:", temper);
      setDataSw(sw);
      setDataTemper(temper);
      setDataA(a);
      setDataW(w);
      setDataV(v);
      setDataHz(hz);
      setDataErr(err);
    }));
  }
  useEffect(() => {
    /*       setDataSw([]);
          setDataTemper([]);
          setDataA([]);
          setDataW([]);
          setDataV([]);
          setDataHz([]);
          setDataErr([]); */
    reloaddata();
    /*     run().then((res => {
          // console.log("res:", res);
          const sw = sw_item_change(res?.datasw || []);
          const temper = temper_item_change(res?.datatemper || []);
          const a = a_item_change(res?.dataa || []);
          const v = v_item_change(res?.datav || []);
          const w = w_item_change(res?.dataw || []);
          const hz = hz_item_change(res?.datahz || []);
          const err = res?.datasw.filter(item => item._field === '故障').concat(err_item_change(res?.dataerr)) || [];
          // console.log("sw0:", sw);
          // console.log("temper0:", temper);
          setDataSw(sw);
          setDataTemper(temper);
          setDataA(a);
          setDataW(w);
          setDataV(v);
          setDataHz(hz);
          setDataErr(err);
        })); */
  }, [deviceimsi]);

  // const data_new = useRequest(() => { return getProductStatesAllRefreshByImsi(10, "s", deviceimsi, viewValues.viewMode); }, {
  const data_new = useRequest(() => { return getProductStatesAllRefreshById(10, "s", devid, viewValues.viewMode); }, {
    pollingInterval: 10000,  // 10000
    pollingWhenHidden: false,
  }).data;

  // dataSw:6
  useEffect(() => {
    // console.log(dataA.length,":",dataA)
    //  console.log(data_new?.dataa.length,":",data_new?.dataa)
    if (dataA.length <= 3600) {
      setDataSw((sw) => sw.concat(sw_item_change(data_new?.datasw || [])));
      setDataTemper((temper) => temper.concat(temper_item_change(data_new?.datatemper || [])));
      setDataA((a) => a.concat(a_item_change(data_new?.dataa || [])));
      setDataV((v) => v.concat(v_item_change(data_new?.datav || [])));
      setDataW((w) => w.concat(w_item_change(data_new?.dataw || [])));
      setDataHz((hz) => hz.concat(hz_item_change(data_new?.datahz || [])));
      setDataErr((err) => err.concat(err_item_change(data_new?.dataerr || [])).concat((data_new?.datasw || []).filter(item => item._field === '故障')));
    } else {
      reloaddata();
    }
  }, [data_new]);

  // console.log("err:",dataErr)
  // console.log("sw:",(data_new?.datasw || []).filter(item => item._field ==="故障"))
  // console.log("temper:", dataTemper);
  const viewValuesCom = async (values: any) => {
    // console.log(values);
    const startTime = dayjs(values.dateTimeRange[0], 'YY-MM-DD HH:mm:ss', 'es').unix();
    const stopTime = dayjs(values.dateTimeRange[1], 'YY-MM-DD HH:mm:ss', 'es').unix();
/*     const influxSearchParam: API.InfluxSearchParam = {
      bucket: "yjy",
      forepartTime: 0,  // 提前时间，单位分钟
      start: startTime,
      stop: stopTime,
      measurement: "ZC",
      tag: deviceimsi,
      field: "SDC_A",
    }
    if (values.viewMode) {
      influxSearchParam.forepartTime = values.forepartTime;
      influxSearchParam.start = 0;
      influxSearchParam.stop = 0;
    } */
    // console.log("influxSearchParam:", influxSearchParam)
    // getInfluxDataCount(influxSearchParam).then((resp) => {
    getProductInfluxDataCountById(devid, values).then((resp) => {
      if (resp.success) {
        if (resp.data > 7200) {
          message.error('数据量太大，请缩短时间间隔，提交失败');
        } else {
          console.log("setview");
          setViewValues((v) => {
            v.viewMode = values.viewMode;
            if (values.viewMode) {
              v.forepartTime = values.forepartTime;
              v.refreshTime = values.refreshTime;
            } else {
              v.startTime = startTime;
              v.stopTime = stopTime;
            }
            return v;
          });
          reloaddata();
          console.log("viewValues:", viewValues);
          message.success('提交成功');
        }
      }
    }).catch(() => {
      message.error('网络数据错误，提交失败');
    })


    /*       const  d3 = dayjs("2022-02-01 09:00:00", 'YY-MM-DD HH:mm:ss','es');
          const  d4 =dayjs("2022-02-02 09:00:00", 'YY-MM-DD HH:mm:ss','es');
          console.log(d3.unix(),d4.unix(),":",d4.unix()-d3.unix())  // 一天 24*3600  */
    // if (!values.viewMode && (stopTime - startTime) > 24 * 3600) {
  };

  const configSw = {
    data: dataSw,
    xField: '_time',
    yField: 'value',
    seriesField: '_field',
    legend: { position: 'top' },
    smooth: true,
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
  };
  // *******************
  const configTemper = {
    data: dataTemper,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',

    /*  // 数据刷新 legend 会恢复（bug?)
         yAxis: {
          label: {
            formatter: function formatter(v: any) {
              return ''.concat(v, '︒C');
            },
          },
        },
        xAxis: {
          label: {
            formatter: function formatter(v: any) {
              return ''.concat(v);
            },
          },
        }, */
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
  };
  // *******************
  const configHz = {
    data: dataHz,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    yAxis: {
      label: {
        formatter: function formatter(v: any) {
          return ''.concat(v, 'Hz');
        },
      },
    },
    xAxis: {
      /*       label: {
              formatter: function formatter(v: any) {
                return '时间'.concat(v);
              },
            }, */
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
    // 不能与animation并用
    /*   slider: {
        start: 0.1,
        end: 0.5,
      }, */
  };
  // *******************
  const configA = {
    data: dataA,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    yAxis: {
      label: {
        formatter: function formatter(v: any) {
          return ''.concat(v, 'A');
        },
      },
    },
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
    // 不能与animation并用
    /*   slider: {
        start: 0.1,
        end: 0.5,
      }, */
  };
  // *******************
  const configV = {
    data: dataV,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    yAxis: {
      label: {
        formatter: function formatter(v: any) {
          return ''.concat(v, 'V');
        },
      },
    },
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
    // 不能与animation并用
    /*   slider: {
        start: 0.1,
        end: 0.5,
      }, */
  };
  // *******************
  const configW = {
    data: dataW,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    yAxis: {
      label: {
        formatter: function formatter(v: any) {
          return ''.concat(v, 'W');
        },
      },
    },
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
    // 不能与animation并用
    /*   slider: {
        start: 0.1,
        end: 0.5,
      }, */
  };
  // *******************
  const configErr = {
    data: dataErr,
    xField: '_time',
    yField: '_value',
    seriesField: '_field',
    /*     yAxis: {
          label: {
            formatter: function formatter(v: any) {
              return '故障'.concat(v);
            },
          },
        }, */
    xAxis: {
      // tickCount: 5,
      type: 'time',
      mask: 'YY-MM-DD HH:mm:ss',
    },
    padding: 'auto',
    legend: { position: 'top' },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 300,
      },
    },
    // 不能与animation并用
    /*   slider: {
        start: 0.1,
        end: 0.5,
      }, */
  };

  // =====================
  let online: string;
  // const updatetime = new Date(initialState?.device_record?.status?.updatetime || "");
  const updatetime = new Date(product?.status?.updatetime || "");
  const now = new Date();
  // 60 * 1000 * 10 10分钟
  // 60 * 1000 * 10 1分钟
  let offTime: number = 5 + 5;
  if (product?.status?.controlsw.con) {
    offTime = 5;
  }

  if ((now.valueOf() - updatetime.valueOf() < 60 * 1000 * offTime)) {
    online = "在线";
  } else {
    online = "离线";
  };

  // const con = product?.status?.controlsw.con ? "开机" : "关机";
  const a = product?.status?.deverr ? "：" : "";
  let run_mode: string = "关机";
  if (product?.status?.controlsw.con) {
    switch (product?.status?.controls.cmode) {
      case 0:
        run_mode = "自动";
        break;
      case 1:
        run_mode = "制冷";
        break;
      case 2:
        run_mode = "除湿";
        break;
      case 3:
        run_mode = "送风";
        break;
      case 4:
        run_mode = "制热";
        break;
      default:
        run_mode = "开机";
        break;
    }
  }
  const status = run_mode + a + product?.status?.errstr;
  return (
    <>
      {!deviceimsi ? (
        <div>
          请先选择一个产品
        </div>
      ) : (
        <>
          <Descriptions title="产品状态" size="small" column={3} bordered>
            <Descriptions.Item label="类别">{product?.devicetype}</Descriptions.Item>
            <Descriptions.Item label="型号">{product?.devicemodel}</Descriptions.Item>
            <Descriptions.Item label="标识">{product?.devlabel}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Badge status={product?.status?.deverr ? "error" : "processing"} text={status} />
            </Descriptions.Item>
            <Descriptions.Item label="在线">
              <Badge status={online === "离线" ? "default" : "processing"} text={online} />
            </Descriptions.Item>
            <Descriptions.Item label="更新时间">{moment(product?.status?.updatetime).format('YYYY-MM-DD HH:mm:ss')}</Descriptions.Item>
            <Descriptions.Item label="设温">{product?.status?.controls.ctemper}︒C</Descriptions.Item>
            <Descriptions.Item label="室温">{product?.status?.states.stemper_in}︒C</Descriptions.Item>
            <Descriptions.Item label="环温">{product?.status?.states.stemper_out}︒C</Descriptions.Item>
            <Descriptions.Item label="管温">{product?.status?.states.stemper_in_pipe}︒C</Descriptions.Item>
            <Descriptions.Item label="排温">{product?.status?.states.stemper_ex}︒C</Descriptions.Item>
            <Descriptions.Item label="功率">{product?.status?.states.sdc_w}</Descriptions.Item>
            <Descriptions.Item label="电压">{product?.status?.states.sdc_v}</Descriptions.Item>
            <Descriptions.Item label="电流">{product?.status?.states.sdc_a}</Descriptions.Item>
            <Descriptions.Item label="频率">{product?.status?.states.scompress_hz}</Descriptions.Item>
          </Descriptions>

          <ProCard>
            <ProForm
              layout={'inline'}
              onFinish={viewValuesCom}
              initialValues={{
                viewMode: 1,
                forepartTime: 30,
                refreshTime: 10000,
                // dateTimeRange: ['2022-02-01 09:00:00', '2022-02-01 18:00:00'],
                dateTimeRange: [dayjs().subtract(3, 'hour').format('YYYY-MM-DD HH:mm:ss'), dayjs().format('YYYY-MM-DD HH:mm:ss')],
              }}
              submitter={{
                // 配置按钮文本
                searchConfig: {
                  submitText: '提交',
                },
                // 配置按钮的属性
                resetButtonProps: {
                  style: {
                    // 隐藏重置按钮
                    display: 'none',
                  },
                },
              }}
            >
              <ProFormSelect
                allowClear={false}
                name="viewMode"
                label="曲线图类型"
                options={[
                  { label: '实时数据', value: 1 },
                  { label: '历史数据', value: 0 },
                ]}
                tooltip="选择曲线图类型"
                placeholder="时间段" />
              {/*  ProFormDependency 会自动注入并且 进行 shouldUpdate 的比对  */}
              <ProFormDependency name={['viewMode']}>
                {({ viewMode }) => {
                  const hidden: boolean = viewMode;
                  return <><></>
                    <ProFormSelect
                      allowClear={false}
                      hidden={!hidden}
                      name="forepartTime"
                      label="前段时间值"
                      options={[
                        { label: '15分钟', value: 15 },
                        { label: '30分钟', value: 30 },
                        { label: '1小时', value: 60 },
                        { label: '2小时', value: 120 },
                        { label: '3小时', value: 180 },
                        //   { label: '4小时', value: 240 },
                        //   { label: '8小时', value: 480 },
                      ]}
                      tooltip="选择前期时间段的数据，之后实时刷新"
                      placeholder="前时间段" />
                    <ProFormSelect
                      hidden={true} // 请求为const,不能更改，不用此refreshTime参数更新
                      allowClear={false}
                      name="refreshTime"
                      label="刷新时间"
                      options={[
                        { label: '10秒', value: 10000 },
                        { label: '20秒', value: 20000 },
                        { label: '30秒', value: 30000 },
                        { label: '40秒', value: 40000 },
                        { label: '50秒', value: 50000 },
                        { label: '60秒', value: 60000 },
                      ]}
                      tooltip="输入实时曲线刷新时间"
                      placeholder="刷新时间" />
                    <ProFormDateTimeRangePicker
                      hidden={hidden}
                      allowClear={false}
                      name="dateTimeRange"
                      label="日期时间区间"
                      tooltip="选择数据时间段，不超过24小时" />
                  </>;
                }}
              </ProFormDependency>
            </ProForm>
          </ProCard>

          <GridContent>
            <ProCard.Group>
              <ProCard>
                <Suspense fallback={null}>
                  <Line {...configSw} />
                  <Line {...configTemper} />
                </Suspense>
                <Suspense fallback={null}>
                  <Line {...configHz} />
                </Suspense>
              </ProCard>
            </ProCard.Group>
            <ProCard.Group>
              <ProCard title="产品参数" ghost collapsible>
                <Suspense fallback={null}>
                  <Line {...configW} />
                  <Line {...configA} />
                  <Line {...configV} />
                </Suspense>
                {/* </ProCard>
      <ProCard title="电流" ghost collapsible> */}
                {/*                 <Suspense fallback={null}>
                      <Line {...configA} />
                    </Suspense> */}
                {/* </ProCard>
      <ProCard title="电压" ghost collapsible> */}
                {/*                 <Suspense fallback={null}>
                      <Line {...configV} />
                    </Suspense> */}
              </ProCard>
            </ProCard.Group>
            <Suspense fallback={null}>
              <Line {...configErr} />
            </Suspense>
            {/*         <Suspense fallback={null}>
              <Line {...config2} />
            </Suspense> */}
          </GridContent></>
      )}
    </>
  );
};

export default DevStates;